package com.hframe.rights;

import com.hframe.data.DRef;
import com.hframe.type.TArray;
import com.hframe.type.TString;
import com.hframe.xml.XmlToData;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import java.io.FileInputStream;
import java.io.InputStream;

/**
 * 权限结构
 *
 * @author Administrator
 */
public class RightsStruct {
    private static Logger log = Logger.getLogger(RightsStruct.class);
    private TArray<DataStruct> rights = new TArray<>(DataStruct.class);
    private static RightsStruct Interface = null;

    public static RightsStruct get() {
        if (null == Interface) {
            Interface = new RightsStruct();
        }
        return Interface;
    }

    public RightsStruct() {
        reload();
    }

    /**
     * 重新加载
     */
    public void reload() {
        String propertiesPath = this.getClass().toString();
        int index = propertiesPath.lastIndexOf(".");
        propertiesPath = propertiesPath.substring(index + 1, propertiesPath.length());
        try {
            InputStream in = this.getClass().getResourceAsStream(propertiesPath + ".xml");
            parse(in);
            in.close();
        } catch (Exception e) {
            log.error(e, e);
        }
    }

    /**
     * 重新加载
     *
     * @param file 文本路径
     */
    public void reload(String file) {
        try {
            FileInputStream in = new FileInputStream(file);
            parse(in);
            in.close();
        } catch (Exception e) {
            log.error(e, e);
        }
    }

    protected void parse(InputStream in) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document doc = reader.read(in);

        DataStruct struct = new DataStruct();
        XmlToData.convert(doc.getRootElement(),struct);
        this.rights = struct.item;
    }

    public TArray<DataStruct> getRights() {
        return rights;
    }

    public static class DataStruct extends DRef<DataStruct> {
        public TString id = new TString();
        public TString name = new TString();
        public TString url = new TString();
        public TArray<DataStruct> item = new TArray<>(DataStruct.class);
    }
}
